<?php

namespace app\home\controller;
use app\common\model\User as U;
use think\Db;
use think\Cache;
use app\common\validate\User as UserValidate;
class Index extends Base
{
    public function index()
    {
        hook('testhook', ['id'=>1]);
        //置顶文章
        $configTopArticle = Db::name("system")->where("config","topArticle")->value("value");
        $topArticle = Db::name("article")->where("article_id","in",$configTopArticle)->limit(4)->select();
        foreach($topArticle as $key => $item){
            $topArticle[$key]["category_name"] = Db::name("category")->where("id",$item["category_id"])->value("category_name");
        }
        //轮播图文章
        $carouselConfig = Db::name("system")->where("config","carousel")->value("value");
        $carouselArticle = Db::name("article")->field("article_id,title,img")->where("article_id","in", $carouselConfig)->select();
        return view('/index',[
            'topArticle'=>$topArticle,
            'carousel' => $carouselArticle,
        ]);
    }

    public function newList()
    {
        $page = input("page");
        $newList = Db::name('article')
            ->alias('a')
            ->join('user u','a.uid = u.uid')
            ->join('category c','a.category_id = c.id')
            ->field("t_article.article_id,t_article.uid,title,category_name,username,read_count,t_article.create_time,content,img")
            ->order("article_id desc")
            ->page($page,10)
            ->select();

        foreach ($newList as $key=>$new){
            $newList[$key]["introduce"] = strip_tags(htmlspecialchars_decode($new["content"]));
        }
        return json($newList);
    }
   public function login()
  {
    if(request()->isAjax()){
      $data = input("post.");
      if (session("loginCount") === null){
        session("loginCount",1);
      }else{
        session("loginCount",session("loginCount") + 1);
      }

      $UserValidate = new UserValidate();
      if(!$UserValidate->scene("login")->check($data)){
        return ["code" =>0,"count" => session("loginCount"),"msg" => $UserValidate->getError()];
      }

      if (session("loginCount") > 5){
        if(!captcha_check($data["code"])){
          return ["code" =>0,"count" => session("loginCount"), "msg" =>"验证码错误"];
        };

      }

      $where["username"] = $data["username"];
      $where["password"] = md5($data["password"]);
      $userInfo = U::where($where)->find();
      if ($userInfo){
        session("loginUid",$userInfo["uid"]);
        session("loginCount",null);
        return ["code" => 1,"msg" => "登录成功"];
      }
      return ["code" => 0,"count" => session("loginCount"), "msg" => "用户名或密码错误"];
    }else{
      return view("/login");
    }
  }
  public function register()
  {
    if(request()->isAjax()){
      $data = input("post.");
      $UserValidate = new UserValidate();
      if(!$UserValidate->scene("reg")->check($data)){
        return ["code" =>0,"msg" => $UserValidate->getError()];
      }
      if(Cache::get('regEmail') == $data['email'] && Cache::get('regCode') == $data['code'] ){
        $data1["password"] = md5($data["pwd"]);
        $data1["username"] = $data["email"];
        $data1["email"] = $data["email"];
        $userId = Db::name("user")->insertGetId($data1);
        $usergGroup = Db::name("auth_group_user")->insert(["uid" =>$userId ,"group_id" => 2]);
        if($userId && $usergGroup){
          cache('regEmail', NULL);
          cache('regCode', NULL);
          return ["code" =>1,"msg" => "注册成功"];
        }
        return ["code" =>0,"msg" => "注册失败"];
      }else{
        return ["code" =>0,"msg" => "验证码错误"];
      }
    }else {
      return view("/register");
    }
  }
  //注册发送邮箱验证码
  public function regSendEmail()
  {
    $email = input("email");
    $checkmail="/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/";
    if(!preg_match($checkmail,$email)){
      return json(["code" => 0,"msg" => "电子邮箱格式错误"]);
    }
    $code = rand(10000,99999);
    $content = "欢迎注册TnCMS用户，您的注册验证码为:" .$code ."<br />(30分钟内有效)";
    $sendEmail = sendEmail($email,"账号激活",$content);
    if($sendEmail["code"] === 200){
      Cache::set('regEmail',$email,1800);
      Cache::set('regCode',$code,1800);
      return json(["code" =>1,"msg" => $sendEmail["msg"]]);
    }
    return json(["code" =>0,"msg" => $sendEmail["msg"]]);
  }

  //找回密码发送邮箱验证码
  public function pwdSendEmail()
  {
    $email = input("email");
    $checkmail="/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/";
    if(!preg_match($checkmail,$email)){
      return json(["code" => 0,"msg" => "电子邮箱格式错误"]);
    }
    $code = rand(10000,99999);
    $content = "找回TnCMS登录密码，您的验证码为:" .$code ."<br />(30分钟内有效)";
    $sendEmail = sendEmail($email,"【TnCMS】密码找回验证码",$content);
    if($sendEmail["code"] === 200){
      Cache::set('pwdEmail',$email,1800);
      Cache::set('pwdCode',$code,1800);
      return json(["code" =>1,"msg" => $sendEmail["msg"]]);
    }
    return json(["code" =>0,"msg" => $sendEmail["msg"]]); 
  }
  //找回密码
  public function pwdRetrieve()
  {
    $email = input("email");
    $code = input("code");
 
    if(Cache::get('pwdEmail') ==  $email && Cache::get('pwdCode') == $code){
      $password = rand(100000,999999);
      $updatePwd = Db::name("user")->where("email",$email)->update(["password" =>md5($password)]);
      if($updatePwd){
        cache('pwdEmail', NULL);
        cache('pwdCode', NULL);
         $content = "您的新密码为：".$password ."，请牢记并及时更改";
         $sendEmail = sendEmail($email,"【TnCMS】密码重置",$content);
        return json(["code" => 1, "msg" => "新密码已发至您的邮箱，请查收。"]);
      }
      return json(["code" => 0, "msg" =>"系统错误"]);
    }
    return json(["code" => 0, "msg" =>"验证码错误"]);
  }
}